#!/usr/bin/env python
# -*- coding: utf-8 -*-
import db_util as db

def create_table():
    conn = db.get_connector()
    sql_str = '''
                CREATE TABLE `hot_topic_user` (
                `tid` int(11) NOT NULL ,
                `date` varchar(8) NOT NULL, 
                `topic` varchar(50) NOT NULL,
                `user` varchar(20) NOT NULL, 
                `frequency` int(5) NOT NULL,
                `re_user` varchar(20),
                PRIMARY KEY (`tid`)
                )
                '''
    db.op_table(conn, sql_str)
    db.close_connector(conn)

def drop_table():
    conn = db.get_connector()
    sql_str = '''
                DROP TABLE `hot_topic_user`
                '''
    db.op_table(conn, sql_str)
    db.close_connector(conn)
    
def insert(sql_data):
    conn = db.get_connector()
    sql_str = ("INSERT INTO hot_topic_user (date, topic, user, frequency, re_user) \
                VALUES (%s, %s, %s, %s, %s)")
#     sql_data = ('20151001', '00', 'TOPIC1', 50)
    db.insert(conn, sql_str, sql_data)
    db.close_connector(conn)
    
def query_by_date(sql_data):
    conn = db.get_connector()
    sql_str = ("SELECT topic, user, frequency, re_user FROM hot_topic_user \
                WHERE date=%s and topic=%s ORDER BY frequency DESC")
#     sql_data = ('20151001', 'TOPIC1')
    cursor = db.query(conn, sql_str, sql_data)
    result = []
    for (topic, user, hour, frequency, re_user) in cursor:
        result.append([topic, user, hour, frequency, re_user])
    db.close_connector(conn)
    return result

def init_data():
    for date_num in range(20151001, 20151032):
        print date_num
        input_file ='/home/ivy/git/Social/Social/resource/hot_topic_user_count/%d.txt' % date_num
        with open(input_file, 'r+') as f:
            counter = 0
            for line in f:
                if counter == 100:
                    break
                arr = line.strip().split('\t')
                sql_data = (str(date_num), arr[0], arr[1], arr[2], arr[3])  
                insert(sql_data) 
                counter += 1
        f.close()
def main():
    print ''
#     drop_table()
#     create_table()
#     init_data()
    
    
if __name__ == '__main__':
    main()
        